<!--
  Copyright 2019 Hackware SpA <human@hackware.cl>
  This file is part of "Hackware Userland" and licensed under the terms
  of the GNU Affero General Public License version 3, or (at your option)
  a later version. You should have received a copy of this license along
  with the software. If not, see <https://www.gnu.org/licenses/>.
-->

<template>
  <form
    class="login-by-email"
    @submit.prevent="submitLogin"
  >
    <h1>Accede vía email</h1>
    <div
      v-if="errorMessage"
      class="login-error"
    >
      <i class="fa fa-exclamation-triangle" />
      {{ errorMessage }}
    </div>
    <div
      v-if="successMessage"
      class="login-success"
    >
      <i class="fa fa-check-circle" />
      {{ successMessage }}
    </div>
    <input
      id="username"
      v-model="username"
      type="text"
      placeholder="Usuario o email"
      name="username"
      required
      autofocus
    >
    <button
      id="btnRequestEmail"
      type="submit"
    >
      <i class="fa fa-envelope" />
      Solicitar enlace de acceso
    </button>
    <p>
      <router-link :to="{ name: 'login-by-password' }">
        Iniciar sesión con contraseña
      </router-link>
    </p>
  </form>
</template>

<script>
export default {
  name: 'LoginByEmail',
  data() {
    return {
      username: null,
      errorMessage: null,
      successMessage: null,
    };
  },
  methods: {
    submitLogin() {
      const btnRequestEmail = document.getElementById('btnRequestEmail');

      btnRequestEmail.setAttribute('disabled', true);
      this.errorMessage = null;

      const data = { username: this.username };
      if ('redirect_to' in this.$route.query) {
        data.redirect_to = this.$route.query.redirect_to;
      }

      return this.$fetcher.hawesePost('/auth/email-token', data, {}, false)
        .then(response => response.json())
        .then((body) => {
          if ('error' in body) {
            btnRequestEmail.removeAttribute('disabled');
            this.errorMessage = body.error.message;
          } else {
            this.successMessage = `Por favor inicia sesión desde el link enviado a ${body.To[0][0]}`;
          }
        });
    },
  },
};
</script>
